package com.hsgene.discount.service.impl;

import com.hsgene.common.util.result.ApiResult;
import com.hsgene.coupon.domain.GeneticDiscount;
import com.hsgene.coupon.dto.GeneticDiscountDto;
import com.hsgene.coupon.dto.GeneticUserDiscountDto;
import com.hsgene.discount.persistence.GeneticDiscountRepository;
import com.hsgene.discount.persistence.GeneticUserDiscountRepository;
import com.hsgene.discount.service.GeneticDiscountService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 优惠券ServiceImpl
 *
 * @author wangbing
 * @version 1.0, 2018/10/11
 */
@Service
public class GeneticDiscountServiceImpl implements GeneticDiscountService {

    @Resource
    private GeneticDiscountRepository geneticDiscountRepository;

    @Resource
    private GeneticUserDiscountRepository geneticUserDiscountRepository;

    @Override
    public ApiResult<List<GeneticDiscountDto>> queryEffectiveDiscount(String userId) {
        List<GeneticDiscount> discounts = geneticDiscountRepository.queryEffectiveDiscount();
        if (CollectionUtils.isEmpty(discounts)) {
            return ApiResult.succ();
        }
        Map<String, List<GeneticUserDiscountDto>> userDiscountMap = new HashMap<>(16);
        if (StringUtils.isNotBlank(userId)) {
            List<GeneticUserDiscountDto> userDiscounts = geneticUserDiscountRepository.queryAllUserDiscount(userId);
            if (!CollectionUtils.isEmpty(userDiscounts)) {
                userDiscountMap = userDiscounts.stream().collect(Collectors.groupingBy(GeneticUserDiscountDto::getGeneticDiscountId));
            }
        }
        final Map<String, List<GeneticUserDiscountDto>> tempMap = userDiscountMap;
        return ApiResult.succ(discounts.stream().map(e -> {
            GeneticDiscountDto dto = new GeneticDiscountDto();
            BeanUtils.copyProperties(e, dto);
            dto.setReceived(!CollectionUtils.isEmpty(tempMap.get(e.getId())));
            return dto;
        }).collect(Collectors.toList()));
    }
}
